//
//  ZhiFuView.m
//  easyTaxi
//
//  Created by ellenpage on 13-2-21.
//  Copyright (c) 2013年 ellenpage. All rights reserved.
//subject: 标题(10000打车豆)
//body:    正文(10000打车豆,赠送800个)

#import "Constant.h"
#import "ZhiFuView.h"
#import "RequestCMD.h"
#import "SocketObject.h"
#import "PassValueClass.h"
#import "AlixPayOrder.h"
#import "AlixPayResult.h"
#import "AlixPay.h"
#import "DataSigner.h"

bool userEnable;

@interface ZhiFuView ()<UITableViewDataSource,UITableViewDelegate,MFMessageComposeViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *mTBView;
@property (weak, nonatomic) IBOutlet UILabel *priceLbl;
@property (retain, nonatomic) NSMutableArray *dataArray;
@property (assign, nonatomic) NSInteger chooseIndex;


- (IBAction)goBack;
- (IBAction)goToZhiFuBao;
- (IBAction)goToYiZhiFu;

@end

@implementation ZhiFuView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self = [[[NSBundle mainBundle] loadNibNamed:@"ZhiFuView" owner:self options:nil] objectAtIndex:0];
        [self initialData];
    }
    return self;
}

- (IBAction)goBack
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kGetTradeIdNoti object:nil];
    
    [self removeFromSuperview];
}

- (void)initialData
{
    [YouMengEvent YouMengEvent:@"0018"];

    if ([PassValueClass sharedIntance].tradeListArray.count > 0)
    {
        _dataArray = [PassValueClass sharedIntance].tradeListArray;
    }
    
    _mTBView.delegate   = self;
    _mTBView.dataSource = self;
    
    _chooseIndex = 100;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkZhiFuBao) name:kGetTradeIdNoti object:nil];
}

#pragma mark - TableView DataSource - 数据源

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                   reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleBlue;

    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(17, 7, 15, 15)];
    imgView.tag = indexPath.row + 1;
    imgView.image = [UIImage imageNamed:@"deselectBtn.png"];
    
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(41, 5, 224, 21)];
    lbl.tag = indexPath.row + 1;
    lbl.backgroundColor = [UIColor clearColor];
    
    NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row];
    
    NSString *str = nil;
    
    NSString *daCheDouTxt      = [dict objectForKey:kCoin];
    
    NSString *extraDaCheDouTxt = [dict objectForKey:kExtraCoin];
    if ([extraDaCheDouTxt isEqualToString:@"0"])
    {
        str = daCheDouTxt;
    }
    else
    {
        str = [NSString stringWithFormat:@"%@,额外赠送%@",daCheDouTxt,extraDaCheDouTxt];
    }

    lbl.text = str;
    
    [cell.contentView addSubview:imgView];
    [cell.contentView addSubview:lbl];
    
    return cell;
}

#pragma mark - TableView Delegate - tableView 代理

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int i = indexPath.row;
    UIImageView *imgView = (UIImageView *)[self viewWithTag:i + 1];
    [imgView setImage:[UIImage imageNamed:@"selectBtn.png"]];
    
    NSDictionary *dict = [_dataArray objectAtIndex:i];
    NSString *moneyTxt = [NSString stringWithFormat:@"%@元",[dict objectForKey:kMoney]];
    _priceLbl.text = moneyTxt;
    
    _chooseIndex = i;
    [PassValueClass sharedIntance].choosedIndexStr = [NSString stringWithFormat:@"%d",i + 1];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int i = indexPath.row;
    UIImageView *imgView = (UIImageView *)[self viewWithTag:i + 1];
    [imgView setImage:[UIImage imageNamed:@"deselectBtn.png"]];
}

#pragma mark - ZhiFu - 支付方式选择

- (IBAction)goToZhiFuBao
{
    [self userLimits];
    [self requestTradeNo];
}

- (IBAction)goToYiZhiFu
{
    
}


- (void)checkZhiFuBao
{
    [YouMengEvent YouMengEvent:@"0020"];

    NSString *notifuUrlStr = [PassValueClass sharedIntance].notifyUrl;
    if ([notifuUrlStr length] == 0)
    {
        notifuUrlStr = @"http://221.226.150.196:8080/Customer/RechargeCoin";
    }
    
    NSString *tradeNoStr   = [PassValueClass sharedIntance].tradeNo;
    
    _chooseIndex = [[PassValueClass sharedIntance].choosedIndexStr intValue];
    NSDictionary *dict = [_dataArray objectAtIndex:_chooseIndex - 1];
    NSLog(@"%@",dict);
    NSString *str = nil;
    
    NSString *daCheDouTxt      = [dict objectForKey:kCoin];
    
    NSString *extraDaCheDouTxt = [dict objectForKey:kExtraCoin];
    if ([extraDaCheDouTxt isEqualToString:@"0"])
    {
        str = daCheDouTxt;
    }
    else
    {
        str = [NSString stringWithFormat:@"%@,额外赠送%@",daCheDouTxt,extraDaCheDouTxt];
    }

    NSString *moneyTxt = [dict objectForKey:kMoney];

    
    //如果partner和seller数据存于其他位置,请改写下面两行代码
	NSString *partner = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Partner"];
    NSString *seller  = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Seller"];
	
	//partner和seller获取失败,提示
	if ([partner length] == 0 || [seller length] == 0)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
														message:@"缺少partner或者seller。"
													   delegate:self
											  cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
		[alert show];
		return;
	}
	
	/*
	 *生成订单信息及签名
	 *由于demo的局限性，本demo中的公私钥存放在AlixPayDemo-Info.plist中,外部商户可以存放在服务端或本地其他地方。
	 */
	//将商品信息赋予AlixPayOrder的成员变量
	AlixPayOrder *order = [[AlixPayOrder alloc] init];
	order.partner = partner;
	order.seller  = seller;
	order.tradeNO = tradeNoStr;
    //    [self generateTradeNO]; //订单ID（由商家自行制定）
	order.productName = daCheDouTxt; //商品标题
	order.productDescription = str; //商品描述
	order.amount = moneyTxt; //商品价格
	order.notifyURL = notifuUrlStr;
    
//    @"http://221.226.150.196:8080/Customer/RechargeCoin"; //回调URL
	
	//应用注册scheme,在AlixPayDemo-Info.plist定义URL types,用于安全支付成功后重新唤起商户应用
	NSString *appScheme = @"easyTaxi";
	
	//将商品信息拼接成字符串
	NSString *orderSpec = [order description];
	NSLog(@"orderSpec = %@",orderSpec);
	
	//获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
	id<DataSigner> signer = CreateRSADataSigner([[NSBundle mainBundle] objectForInfoDictionaryKey:@"RSA private key"]);
    
	NSString *signedString = [signer signString:orderSpec];
	
	//将签名成功字符串格式化为订单字符串,请严格按照该格式
	NSString *orderString = nil;
	if (signedString != nil)
    {
		orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        //获取安全支付单例并调用安全支付接口
        AlixPay * alixpay = [AlixPay shared];
        int ret = [alixpay pay:orderString applicationScheme:appScheme];
        
        if (ret == kSPErrorAlipayClientNotInstalled)
        {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                 message:@"您还没有安装支付宝快捷支付，请先安装。"
                                                                delegate:self
                                                       cancelButtonTitle:@"确定"
                                                       otherButtonTitles:nil];
            [alertView setTag:123];
            [alertView show];
        }
        else if (ret == kSPErrorSignError)
        {
            NSLog(@"签名错误！");
        }
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (alertView.tag == 123)
    {
		NSString * URLString = @"http://itunes.apple.com/cn/app/id535715926?mt=8";
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLString]];
	}
    if (alertView.tag == kUserLogInAlert)
    {
        if (buttonIndex == 1)
        {
            NSString *str1 = [GetPhoneInfo getCurrentTimeStamp];
            NSString *str2 = [GetPhoneInfo getCurrentIMSI];
            NSString *contentStr = [NSString stringWithFormat:@"CODE=ETAXI,TYPE=PASSENGER,TIMESTAMPS=%@,IMSI=%@",str1,str2];
            
            NSString *teleNoStr = nil;
            if ([PassValueClass sharedIntance].messageGatewayNoStr != nil)
            {
                teleNoStr = [PassValueClass sharedIntance].messageGatewayNoStr;
            }
            else
            {
                teleNoStr = kSignUpNo;
            }
            NSArray *arrry = [NSArray arrayWithObject:teleNoStr];

            NSLog(@"%@",arrry);

            [self sendSMS:contentStr recipientList:arrry];
            
            MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self];
            [self addSubview:HD];
            HD.labelText = @"正在注册,请耐心等待!";
            [HD showAnimated:YES whileExecutingBlock:^{
                //对话框显示时需要执行的操作
                sleep(10);
            } completionBlock:^{[HD removeFromSuperview];}];
        }
    }
}


#pragma mark - Request TradeNo - 请求交易号

- (void)requestTradeNo
{
    NSString *string    = [RequestCMD requestCMD:kRequetTradeID];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kRequetTradeID];
}


#pragma mark - 用户权限管理

- (void)userLimits
{
    if (isTiYanMoShiOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前处在体验模式" message:@"体验模式下仅能查看信息" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    if (!isSokectOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"服务器未连接,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    if (!isAvaliableCityOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你所在的区域不支持我们的服务,敬请期待~"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    if (!isLoginOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络问题导致登录异常,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    //3.判断是否已经绑定手机号
    NSString *isBindedStr = [PassValueClass sharedIntance].isBindedStr;
    if (isBindedStr == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"正在获取个人信息请稍后..."
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
        
    }
    
    if ([isBindedStr isEqualToString:@"0"])
    {
        if (!kIsIphone)
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"检测到您的设备不具备短信和运营商电话功能,请使用iPhone体验本程序~"
                                                                      message:nil
                                                                     delegate:self
                                                            cancelButtonTitle:@"知道了"
                                                            otherButtonTitles:nil, nil];
            
            [signUpAlertView show];
            userEnable = NO;
            return;
        }
        else
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"手机注册"
                                                                      message:@"为了您的交易安全,请发送一条短信,完成注册"
                                                                     delegate:self
                                                            cancelButtonTitle:@"稍后再试"
                                                            otherButtonTitles:@"发送短信", nil];
            signUpAlertView.tag = kUserLogInAlert;
            [signUpAlertView show];
            userEnable = NO;
            return;
        }
    }
    userEnable = YES;
}

#pragma mark - 发送短信

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
//        [self presentModalViewController:self animated:YES];
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
//    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent");
    else
        NSLog(@"Message failed");
}


@end
